<script setup>
import { apiImgUrl } from "@/api";
import { useDetails } from "@/hooks/useDetails";
import { computed } from "vue";
import { rating } from "@/lib/filter";
import { UseImage } from "@vueuse/components";
import { RiFileImageLine, RiLoaderLine } from "vue-icons-plus/ri";

const { item } = defineProps({
  item: {
    type: Object,
    required: true,
  },
});

const { name, stars } = useDetails(item);

const poster = computed(() => {
  if (item.poster_path) {
    return `${apiImgUrl}/w370_and_h556_bestv2${item.poster_path}`;
  } else if (item.profile_path) {
    return `${apiImgUrl}/w370_and_h556_bestv2${item.profile_path}`;
  } else {
    return false;
  }
});

const media = computed(() => {
  if (item.media_type) {
    return item.media_type;
  } else if (item.name) {
    return "tv";
  } else {
    return "movie";
  }
});
</script>

<template>
  <router-link :to="{ name: `${media}Detail`, params: { id: item.id } }">
    <div
      class="bg-secondary p-1 aspect-[10/16] transition duration-300 hover:scale-105 z-10"
    >
      <UseImage
        :src="poster"
        width="200"
        height="600"
        class="size-full object-cover"
        :alt="name"
      >
        <template #loading>
          <div class="flex items-center justify-center size-full">
            <RiLoaderLine class="size-8 animate-spin fill-primary" />
          </div>
        </template>

        <template #error>
          <div class="flex items-center justify-center size-full">
            <RiFileImageLine class="size-9" />
          </div>
        </template>
      </UseImage>
    </div>
    <h2
      class="mt-[10px] overflow-hidden text-[13px] text-ellipsis whitespace-nowrap xl:mb-[5px] xl:text-[15px]"
    >
      {{ name }}
    </h2>
    <div
      v-if="media !== 'person' && (stars || item.vote_average)"
      class="flex items-center"
    >
      <div
        v-if="stars"
        class="w-[73px] h-[12px] bg-[url('@/assets/images/stars.png')] bg-no-repeat [background-size:auto_100%]"
      >
        <div
          class="w-full bg-[url('@/assets/images/stars-filled.png')] bg-no-repeat [background-size:auto_100%]"
          :style="{ width: `${stars}%` }"
        />
      </div>

      <div
        v-if="item.vote_average"
        class="ml-[10px] text-xs text-grey xl:text-[14px]"
      >
        {{ rating(item.vote_average) }}
      </div>
    </div>
  </router-link>
</template>
